import React, { Component } from 'react';
import { connect } from 'react-redux';
import { createAddress, updateAddress } from '../../../store/actions';
import '../../../components/form/input.css'
import 'flex.css/dist/data-flex.css';
import './edit-phone.less'
import './add-address.less'
import Input from 'components/form/input'
import Button from 'components/button/button'
import Toptip from 'components/toptip/toptip'
import { validForm, validValue } from 'Utils/lite-validator.js'
import _ from 'lodash'

import { Picker, List } from 'antd-mobile'
import { createForm } from 'rc-form'
import { district } from 'assets/data'

@connect(
  state=>state.address
)
export default class AddAddressPage extends Component {
  constructor(){
    super();
    this.state={
      errMsg: '',
      errShow:false,
      errTimmer:null,
      disabled: true,
      isEdit: false,
      editId: '',
      addressPickerValue:[],
      formData:{
        addressName:'',
        'default': false,
        firstName:'',
        phonePrimary:'',
      }
    }
    this.getAddressInfo = this.getAddressInfo.bind(this);
  }
  getAddressInfo(){
    let [stateProvinceRegion, city, county] = this.state.addressPickerValue,
        addressInfo=[], p1, p2;
    if(stateProvinceRegion){
      p1 = _.find(district, { value: stateProvinceRegion });
      addressInfo.push(p1);
    }
    if(city && p1){
      p2 = _.find(p1.children, { value: city });
      addressInfo.push(p2);
    }
    if(county && p2){
      addressInfo.push(_.find(p2.children,  { value: county }));
    }

    return addressInfo.map(v=>v.label);
  }
  getAddressInfoByStr(addressArr){
    let [stateProvinceRegion, city, county] = addressArr,
        addressInfo=[], p1, p2;

    if(addressArr[0]){
      p1 = _.find(district, { label: stateProvinceRegion });
      addressInfo.push(p1);
    }
    if(city && p1){
      p2 = _.find(p1.children, { label: city });
      addressInfo.push(p2);
    }
    if(county && p2){
      addressInfo.push(_.find(p2.children,  { label: county }));
    }

    return addressInfo.map(v=>v.value);
  }
  updateState(stateName){
    return e => {
      let v= e.target.value;
      this.setState({
        'formData':{
          ...this.state.formData,
          [stateName]:v
        }
      })
    }
  }
  componentDidMount(){
    const addressId  = ~~this.props.location.query.id;
    if(addressId && this.props.list){
      const editItem = this.props.list.filter(v=>v.id === addressId)[0];
      if(editItem){
        let addressArr = this.getAddressInfoByStr([editItem.stateProvinceRegion, editItem.city, editItem.county]);
        this.setState({
          isEdit:true,
          editId: addressId,
          addressPickerValue:addressArr,
          formData:{
            'default': editItem.default,
            firstName: editItem.firstName,
            phonePrimary: editItem.phoneNumber,
            addressName: editItem.addressName
          }
        })
      }
    }
  }
  componentWillUnmount(){
    this.state.errTimmer && clearTimeout(this.state.errTimmer);
  }
  showWran(msg){
    this.state.errTimmer && clearTimeout(this.state.errTimmer);
    this.setState({
      errShow: true,
      errMsg: msg,
      errTimmer: setTimeout(()=>{
        this.setState({ errShow: false })
      }, 3000)
    })
  }
  valide(){
    var oFormBox = this.refs.formBoxAddAddress;

    return validForm(oFormBox, {
      'firstName':[['required'],['length:~6','字符长度过长，请小于6个字符']],
      'phonePrimary': [['required'],['phone','请输入正确的联系方式']],
      'addressName': [['required']],
    })
  }
  handleSubmit( e ) {
    var pms = { address:{...this.state.formData} };
    console.log(pms);
    this.valide().then(res=>{
      var addressInfo = this.getAddressInfo();
      if(!addressInfo.length){
        return this.showWran('请选择省市区');
      }
      pms.address.stateProvinceRegion = addressInfo[0];
      pms.address.city = addressInfo[1];
      pms.address.county = addressInfo[2]||'';

      var params = {
        'address.addressLine1': pms.address.addressName,
        'address.stateProvinceRegion': pms.address.stateProvinceRegion,
        'address.city': pms.address.city,
        'address.county': pms.address.county,
        'address.default': pms.address.default,
        'address.firstName': pms.address.firstName,
        'address.phonePrimary': pms.address.phonePrimary,
        'addressName': pms.address.addressName,
        'address.isoCountryAlpha2':'CN',
      }
      this.state.isEdit
      ? this.props.dispatch(updateAddress(_.merge(params, {customerAddressId: this.state.editId})))
      : this.props.dispatch(createAddress(params));
    }).catch(err=>{
      if(err instanceof Error) throw err;
      err.el.focus();
      err.el.parentElement.classList.add('error');
      this.showWran(err.msg || '输入信息不正确');
    })
  }
  handleIptClick(e){
    e.target.parentElement.classList.remove('error')
  }
  render () {
    const formData = this.state.formData;

    return (
      <div ref="formBoxAddAddress" className="edit-phone-frm pt20 page-scroll-view">

      <div className="shadow bg-wt">
        <div className="ui-ipt-group bdr-t" data-flex="">
          <label className="ui-ipt-label bdr-r label-icon" data-flex-box="0">收货人</label>
          <input type="text" className="ui-ipt" value={formData.firstName} name="firstName" placeholder="请输入收货人姓名" data-flex-box="1"
            onChange = { this.updateState('firstName') }
            onClick = { this.handleIptClick }
          />
        </div>
        <div className="ui-ipt-group ui-form-line" data-flex="">
          <label className="ui-ipt-label bdr-r label-icon" data-flex-box="0">联系电话</label>
          <input type="text" className="ui-ipt" value={formData.phonePrimary || ''} name="phonePrimary" placeholder="请输入联系电话" data-flex-box="1"
            onChange = { this.updateState('phonePrimary') }
            onClick = { this.handleIptClick }
          />
        </div>
        <div className="ui-ipt-group ui-form-line address-control">
          <Picker extra="请选择省市区" title="选择地区" ref="picker"
          data = {district}
          value = { this.state.addressPickerValue }
          onChange = { (v)=>this.setState({ addressPickerValue : v }) }
          >
          <List.Item arrow="horizontal">所在地区</List.Item>
        </Picker>
        </div>
        <div className="bt-wt address-area" data-flex="">
          <textarea className="ui-ipt-textarea" value={formData.addressName} name="addressName" cols="30" rows="10" placeholder="请输入详细地址"
            onChange = { this.updateState('addressName') }
            onClick = { this.handleIptClick }
          ></textarea>
        </div>
      </div>

        <div className="btn-fixed-bottom">
          <Button
            onClick={this.handleSubmit.bind(this)}
          >保存</Button>
        </div>

        <Toptip show={this.state.errShow} type="warn">{this.state.errMsg}</Toptip>
    </div>
    )
  }
}
